package m202401.d12;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/1/12 09:16
 */
//117. 填充每个节点的下一个右侧节点指针 II
public class Q117 {
    public static void main(String[] args) {
        Node n1 = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);
        Node n4 = new Node(4);
        Node n5 = new Node(5);
        Node n7 = new Node(7);
        n1.left = n2;
        n1.right = n3;
        n2.left = n4;
        n2.right = n5;
        n3.right = n7;

        new Q117().connect(n1);
    }

    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        LinkedList<Node> current = new LinkedList<>();
        LinkedList<Node> next = new LinkedList<>();
        current.addLast(root);
        Node p = null;
        while (!current.isEmpty() || !next.isEmpty()) {
            if (current.isEmpty()) {
                current = next;
                p = null;
                next = new LinkedList<>();
                continue;
            }
            Node node = current.removeFirst();
            if (p == null) {
                p = node;
            } else {
                p.next = node;
                p = p.next;
            }
            if (node.left != null) {
                next.addLast(node.left);
            }
            if (node.right != null) {
                next.addLast(node.right);
            }
        }
        return root;
    }


    static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    ;
}
